package helpers

import (
	"time"
	"log"
	"net/smtp"
	"strings"
	"io/ioutil"
	"fmt"
	"os"
	"crypto/md5"
	"net/url"
)

//获取时间戳
//golang 的时间参考标准是 2006-01-02 15:04:05
func GetUnix(needTime string, format string) int64 {
	times, err := time.Parse(format, needTime)
	if err != nil {
		log.Println(err)
		return 0
	}
	return times.Unix()
}


//发送邮件
func SetMail(toEmails[]string, msg, title string) error {
	hp := "smtp.qq.com:25"
	auth := smtp.PlainAuth("", "3091597759@qq.com", "jxfwoqykehtodeai", "smtp.qq.com")
	tos := strings.Join(toEmails, ";")
	content_type := "Content-Type: text/plain" + "; charset=UTF-8"
	message := []byte("To: " + tos + "\r\nFrom: " + "3091597759@qq.com" + "<" + "3091597759@qq.com" + ">\r\nSubject: " + title + "\r\n" + content_type + "\r\n\r\n" + msg)
	err := smtp.SendMail(hp, auth, "3091597759@qq.com", toEmails, message)
	return err
}


//读取文件内容
func ReadFile(fName string) (string, error) {
	by, err := ioutil.ReadFile(fName)
	if err != nil {
		return "", err
	}
	return string(by), nil
}


//判断文件是否存在
func Exist(filename string) bool {
	_, err := os.Stat(filename)
	return err == nil || os.IsExist(err)
}

//MD5函数
func Md5(str string) string {
	md := md5.Sum([]byte(str))
	return fmt.Sprintf("%x", md)
}

func UrlEncoded(str string) (string) {
	u, err := url.ParseRequestURI(str)
	if err != nil {
		log.Fatal(err)
	}
	return u.Scheme + "://" + u.Host + u.Path + "?" + u.Query().Encode()
}

func UrlDecode(ustr string) string {
	s, err := url.QueryUnescape(ustr)
	if err != nil {
		return ustr
	}
	return s
}

